package com.yc.http.v1.impl;

import com.yc.http.v1.*;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpServletResponseImpl implements HttpServletResponse {

    OutputStream out;
    // 结果码
    private int status = 200;
    private String msg = "OK";
    // 字符串输出流 => 内存
    CharArrayWriter caw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(caw);
    // 头域参数集合
    private Map<String,String> headerMap = new HashMap<>();
    // 请求对象
    private HttpServletRequest request;
    //  cookie 集合
    private List<Cookie> cookieList = new ArrayList<>();

    public HttpServletResponseImpl(Socket socket, HttpServletRequest request) {
        try {
            this.request = request;
            out = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PrintWriter getWriter() {
        return pw;
    }

    @Override
    public OutputStream getOutputStream() {
        return out;
    }

    @Override
    public void setContentType(String type) {
        setHeader("Content-Type", type);
    }

    @Override
    public void setStatus(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    @Override
    public void setHeader(String name, String value) {
        headerMap.put(name, value);
    }

    @Override
    public void flushBuffer() {
        // 响应头行
        try {
            out.write(String.format("%s %s %s\n",
                    request.getProtocol(), status, msg).getBytes());
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                // 头域参数
                out.write(String.format("%s: %s\n",
                        entry.getKey(), entry.getValue()).getBytes());
            }
            for (Cookie cookie : cookieList) {
                out.write(String.format("Set-Cookie: %s\n",cookie.toString()).getBytes());
            }
            // 将请求中的会话对象的id 发送给浏览器
            HttpSession session = request.getSession();
            out.write(String.format("Set-Cookie: %s=%s\n",
                    "JSESSIONID",
                    session.getId()).getBytes());

            // 空行
            out.write(String.format("\n").getBytes());
            // 内容 body
            if (status == 200){
                // 获取字符串输出流中的数据
                final String content = caw.toString();
                out.write(content.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void sendRedirect(String location) {
        // 设置结果码 301
        // 设置重定向地址: Location
        setStatus(301, "Redirect");
        setHeader("Location", location);
    }

    @Override
    public void addCookie(Cookie cookie) {
        cookieList.add(cookie);
    }
}
